package com.ling.feign.plus.aspect;

import com.ling.feign.plus.exception.BaseFeignServerBusinessException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;

@Aspect
@Component
public class FeignClientAspect {

    @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping) " +
            "|| @annotation(org.springframework.web.bind.annotation.GetMapping) " +
            "|| @annotation(org.springframework.web.bind.annotation.PostMapping) " +
            "|| @annotation(org.springframework.web.bind.annotation.DeleteMapping) " +
            "|| @annotation(org.springframework.web.bind.annotation.PutMapping) ")
    public void pointCut() {
    }


    @AfterThrowing(pointcut = "pointCut()", throwing = "ex")
    public void afterThrowing(JoinPoint point, Exception ex) throws Exception {
        Annotation annotation = point
                .getSignature()
                .getDeclaringType()
                .getAnnotation(FeignClient.class);

        if (annotation instanceof FeignClient
                && ex instanceof BaseFeignServerBusinessException) {
            BaseFeignServerBusinessException exception = (BaseFeignServerBusinessException) ex;
            throw exception.getBaseException();
        }
        throw ex;

    }

}
